package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.domain.BankAccount;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.IServerBankAccountService;
import com.jzo2o.mvc.utils.UserContext;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class ServerBankAccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements IServerBankAccountService {
    /**
     * 用户服务端 新增或更新银行账户信息接口
     */
    @Override
    public void serverBankAccountAddOrUpdate(BankAccountUpsertReqDTO bankAccount) {
        //首先判断 是新增操作还是更新操作
        //建立表示
        //每个服务人员设置一个银行账户
        BankAccount one = this.lambdaQuery()
                .eq(BankAccount::getId, UserContext.currentUserId())
                .eq(BankAccount::getType, 2)
                .one();
        //如果说新增用户存在 则不允许新增
        if (Objects.isNull(one)) {
            //如果为空那就是新增
            bankAccount.setType(2);
        }
        bankAccount.setId(UserContext.currentUserId());
        //将数据拷贝至POJO实体类
        BankAccount bankAcc = BeanUtils.copyBean(bankAccount, BankAccount.class);
        boolean b = this.saveOrUpdate(bankAcc);
        if (!b) {
            throw new ForbiddenOperationException("新增或更新银行账户出现问题");
        }

    }

    @Override
    public BankAccountResDTO getCurrentUserBankAccount() {
        //首先获取当前登录用户
        //获取当前用户id
        Long userId = UserContext.currentUserId();
        //查询该用户的银行账户信息
        BankAccount one = this.lambdaQuery()
                .eq(BankAccount::getId, userId)
                .one();
        return BeanUtils.copyBean(one, BankAccountResDTO.class);
    }

    /**
     * 新增或更新银行账户信息接口
     * @param bankAccount
     * @return
     */
    @Override
    public BankAccountResDTO addOrUpdateAgencyBankAccount(BankAccountUpsertReqDTO bankAccount) {
        Long userId = UserContext.currentUserId();

        //首先判断 是新增操作还是更新操作
        BankAccount one = this.lambdaQuery()
                .eq(BankAccount::getId, userId)
                .eq(BankAccount::getType, 3)
                .one();
        //获取当前用户id
        if(Objects.isNull(one)){
            bankAccount.setType(3);
        }
        bankAccount.setId(userId); //无论是新增还是更新操作都需要id 而id就是当前用户id
        boolean b = this.saveOrUpdate(BeanUtils.copyBean(bankAccount, BankAccount.class));
        if(!b){
            throw new ForbiddenOperationException("新增或更新银行账户出现问题");
        }
        BankAccount byId = this.getById(userId);
        return BeanUtils.toBean(byId, BankAccountResDTO.class);
    }
}
